




<!--

使用：
1 打开弹框

   /**
     * item 参数信息  { type:{name:'dir || file ',plural:''}......   } 目前其中type属性必须有   file || dir   文件或者文件夹
     * isBatch 文件选择是否是批量 批量（多景处理）多选文件路径间的分隔符以"#HT#" 常规的以"#TASK#"隔开
     */

      this.fileCatalogModal = true;  // 打开弹框
      this.$nextTick(() => {
        that.$refs.refFileCatalogModal.initFileTree(item, isBatch);    //控制文件文件夹   是否多选
      });




2 方法：
@closed="fileCatalogModalClose"
@menuOk="fileCatalogModalOk"
fileCatalogModalOk(data){ // 选择的目录或者文件  }

-->




<template>
  <div class="hheader">
    <Modal
      v-model="fileModalShow"
      draggable
      scrollable
      :transfer="true"
      style="z-index: 100000; position: absolute"
      title="选择目录"
      class="fileCatalogModal"
      :width="menuModalWidth"
    >
      <p slot="header" class="modalHeader">选择目录</p>
      <CButtonClose slot="close" @click="menuCancel" />

      <div class="modalContent">
        <div class="treeDiv">
          <ul :id="ztreeId" class="ztree"></ul>
        </div>
        <div class="resultDiv" id="resultDataDiv" v-show="resultTableShow">
          <span class="selectNumberClass"
            >已选择的数据 {{ resultDataTotal }} 个</span
          >
          <Table
            border
            :columns="getColumn"
            :data="resultData"
            class="resultTableStyle"
          >
            <template slot="action" slot-scope="{ row, index }">
              <CButton
                v-c-tooltip="'删除'"
                title="删除"
                variant="outline"
                color="info"
                size="sm"
                @click="deletePathRow(row, index)"
              >
                <CIcon name="cil-x-circle" />
              </CButton>
            </template>
          </Table>
        </div>
      </div>
      <template #footer>
        <div style="display: flex; width: 100%">
          <div style="width: 50%; display: flex; align-items: center">
            <CInput
              label="筛选:"
              placeholder="关键字"
              style="margin: 0 10px 0 0"
              horizontal
              v-model="filterName"
              :title="filterName"
              maxlength="100"
            />
            <div style="width: 40%">
              <CSelect
                label="类型:"
                horizontal
                :options="suffixOptions"
                :value.sync="currentSelectSuffix"
                @change="suffixSearch()"
                class="selectSuffix"
              ></CSelect>
            </div>
          </div>

          <div style="width: 50%">
            <CButton
              v-if="handleButton"
              @click="handleWorkflow"
              color="info"
              style="width: 80px"
              class="system-btn-style"
              >提交任务</CButton
            >
            <CButton
              @click="createNewFolder"
              color="info"
              title="点击文件夹即可，不需要打钩选中哦~"
              class="system-btn-style"
            >
              {{ saveAsName }}</CButton
            >
            <CButton
              @click="menuOk"
              color="info"
              style="width: 68px"
              class="system-btn-style"
              >确定</CButton
            >
            <CButton
              @click="menuCancel"
              color="info"
              class="cancel-btn"
              style="width: 68px"
              >取消</CButton
            >
            <!-- <CButton
              @click="showSelectedData"
              color="info"
              class="delBtn"
              style="width: 100px"
              >显示选择>></CButton
            > -->
          </div>
        </div>
      </template>
    </Modal>

    <Modal
      v-model="editShow"
      draggable
      scrollable
      title="收藏文件重命名"
      :styles="modalStyle"
      :transfer="true"
      style="z-index: 1000000; position: absolute"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">重命名</span>
      </p>
      <div class="modalBody">
        <span>请填写新的名字：</span>
        <input
          v-model="editName"
          type="text"
          style="height: 35px; width: 280px"
        />
      </div>
      <template #footer class="footerBtns">
        <CButton @click="editShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="editOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <Modal
      v-model="collectShow"
      draggable
      scrollable
      title="收藏文件"
      :styles="modalStyle"
      :transfer="true"
      style="z-index: 1000000; position: absolute"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shoucang.png" width="22px" height="22px" alt />
        <span style="margin-left: 5px">收藏文件</span>
      </p>
      <div class="modalBody">
        <span>请填写名称：</span>
        <input
          v-model="collectName"
          type="text"
          style="height: 35px; width: 280px"
        />
      </div>
      <template #footer class="footerBtns">
        <CButton @click="collectShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="collectOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <Modal
      v-model="delShow"
      draggable
      scrollable
      title="删除收藏内容"
      :styles="modalStyle"
      :transfer="true"
      style="z-index: 1000000; position: absolute"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">删除收藏内容</span>
      </p>
      <div class="modalBody">
        <p>删除后所收藏内容都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <Modal
      v-model="changeShow"
      draggable
      scrollable
      title="收藏文件路径已改变"
      :styles="modalStyle"
      :transfer="true"
      style="z-index: 1000000; position: absolute"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/clear.png" width="22px" height="22px" alt />
        <span style="margin-left: 5px">收藏文件路径已改变</span>
      </p>
      <div class="modalBody">
        <p>该收藏文件/文件夹的路径已改变</p>
        <p>如有需要请重新收藏</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="changeShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton
          @click="changeShow = false"
          color="info"
          class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <Modal
      v-model="createFolderModal"
      draggable
      scrollable
      title="新增"
      class="menuModal"
      :styles="modalStyle"
      :transfer="true"
      style="z-index: 1000000; position: absolute"
    >
      <p slot="header" class="modalHeader">新增</p>
      <CButtonClose slot="close" @click="createFolderCancel" />
      <div class="saveFile">
        <CInput
          label="文件:"
          class="saveFileStyle"
          horizontal
          v-model="newFileName"
          v-show="fileInput"
        />
      </div>
      <div class="saveFolder">
        <CInput
          label="文件夹:"
          class="saveFileStyle"
          horizontal
          v-model="newFileName"
          v-show="folderInput"
        />
      </div>
      <template #footer>
        <CButton @click="createFolderOk" color="info" class="system-btn-style"
          >确定</CButton
        >
        <CButton @click="createFolderCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
      </template>
    </Modal>
  </div>
</template>
<script>
import { mapGetter, mapGetters, mapMutations } from "vuex";
import imgData from "../../assets/icons/delete.svg";
import "../../utils/jquery.ztree.exhide.min.js";
export default {
  name: "fileCatalog",

  props: {
    modalShow: {
      type: Boolean,
      default: false,
    },
    requestType: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      fileModalShow: false,
      ztreeId: "ztree_" + parseInt(Math.random() * 1e10),
      modalStyle: { top: "300px" },
      menuModalWidth: 1000,
      suffixOptions: [],
      currentSelectSuffix: "",
      filterName: "", //关键字
      dataList: [],
      suffixChangeState: false, //记录当前后缀是否改变用于目录树更新
      currentItem: "",
      resultData: [],
      resultTableShow: true,
      resultDataTotal: 0,

      createFolderModal: false,
      isFile: false,
      newFileName: "",
      fileInput: false,
      folderInput: true,

      delShow: false, //删除Modal框
      deletePath: "", //记录删除的文件路径

      editShow: false, //收藏文件重命名
      editPath: "", //记录收藏的文件路径
      editName: "", //记录收藏的文件名

      changeShow: false, //记录文件路径已改变的收藏文件

      collectShow: false, //收藏Modal框
      collectPath: "", //记录收藏文件路径
      collectName: "", //记录收藏文件的新名称

      handleButton: false, //是否显示执行任务按钮
      isBatch: true,
      saveAsName: "新建文件",
      setTimeoutTime: "",

      collectItem: "",
      dataListOne: "",

      node: "", //记录当前zTree节点名称
      _node: "",
      ztreeNode: [],
    };
  },
  watch: {
    filterName() {
      this.selectFileName();
    },
    modalShow: {
      handler(val) {
        this.fileModalShow = val;
        if (!val) {
          this.filterName = ""; //关闭弹框搜索名字清空
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapMutations(["setCollectTreeNode"]),
    ...mapGetters(["getCollectTreeNode"]),
    getColumn() {
      return [
        {
          key: "name",
          title: "名称",
          align: "center",
          width: "auto",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.path,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.name
              ),
            ]);
          },
        },
        {
          title: "操作",
          width: "80px",
          slot: "action",
          align: "center",
        },
      ];
    },
  },
  methods: {
    /**
     * 删除收藏文件目录下的一级文件/文件夹
     */
    delOk() {
      this.delShow = false;
      let path =
        this.$api.processingApi.deleteCollections + "?path=" + this.deletePath;
      this.http.delete(path).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success(res.data.message);
          var zTreeObj = $.fn.zTree.getZTreeObj(this.ztreeId);
          var parentNode = this.node.getParentNode(); //获取当前节点的父节点
          zTreeObj.updateNode(parentNode); //更新节点
          zTreeObj.selectNode(parentNode);
          zTreeObj.removeNode(this.node); //删除选中的节点

          let _node = this.node;
          let _treeDataChildren = this.getCollectTreeNode[0].children;
          let _treeData = this.getCollectTreeNode;
          let index = _treeDataChildren.findIndex((item) => {
            if (item.id == _node.id) {
              return true;
            }
          });
          _treeDataChildren.splice(index, 1);

          this.$store.commit("setCollectTreeNode", _treeData);

          if (parentNode.children.length == 0) {
            //如果所有的子节点都删除了，需要更新一下父节点，不然图标会变为文件形式
            parentNode.isParent = true;
            parentNode.open = true;
            zTreeObj.updateNode(parentNode);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    /**
     * 重命名收藏文件目录下的一级文件/文件夹
     */
    editOk() {
      this.editShow = false;
      let path =
        this.$api.processingApi.updateCollections + "?path=" + this.editPath;
      let params = {
        path: "",
        pathName: this.editName,
      };
      this.http.put(path, params).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success("修改成功！");
          var zTreeObj = $.fn.zTree.getZTreeObj(this.ztreeId);
          this.node.name = this.editName; //修改后的新名字
          zTreeObj.updateNode(this.node); //更新修改后的节点
          zTreeObj.reAsyncChildNodes(this.node, "refresh", false);

          let _node = this.node;
          let _treeDataChildren = this.getCollectTreeNode[0].children;
          let _treeData = this.getCollectTreeNode;
          let index = _treeDataChildren.findIndex((item) => {
            if (item.id == _node.id) {
              item.name = this.editName;
            }
          });
          // _treeDataChildren.splice(index,1)
          this.$store.commit("setCollectTreeNode", _treeData);
        } else {
          this.$Message.error("修改失败！");
        }
      });
    },
    /**
     * 收藏文件
     */
    collectOk() {
      let that = this;

      this.collectShow = false;
      let path = this.$api.processingApi.collectFiles;
      let params = {
        path: this.collectPath,
        pathName: this.collectName,
      };
      this.http.post(path, params).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success("收藏成功！");
          // let _ztreeNode = that.getCollectTreeNode; //获取到整棵树（改变之前的树）
          let _node = JSON.parse(JSON.stringify(that.node)); //_node节点 深拷贝 node节点  不然共享文件下的文件也会改变
          _node.isDelete = true; //新增节点的isDelete字段置为true 即表示可以进行删除、修改
          _node.name = that.collectName; //新增节点的名字
          //   _ztreeNode[0].children.push(that._node);//把新增的节点添加到“用户的收藏目录”下

          var ztreeObj = $.fn.zTree.getZTreeObj(that.ztreeId); //定义zTree
          var nodes = ztreeObj.getNodes(); //获取到整棵树的节点  3个： 收藏目录 共享文件  用户文件
          let treeNode = ztreeObj.getNodeByTId(nodes[0].tId); //通过id获取第一个节点 即“用户的收藏目录”
          ///  ztreeObj.removeChildNodes(treeNode);//把获取到的第一个节点从树中移除
          ztreeObj.addNodes(treeNode, 0, _node); //把新的节点作为树的第一个节点 插入进去
          // ztreeObj.moveNode(treeNode[0], treeNode[treeNode.length], "prev");
        } else {
          that.$Message.error(res.data.message);
        }
      });
    },

    selectFileName() {
      //节流控制搜索组织机构数
      let that = this;
      var treeObj = $.fn.zTree.getZTreeObj(this.ztreeId);
      var nodeArr = treeObj.transformToArray(treeObj.getNodes());
      if (that.filterName.trim()) {
        that.dataList = nodeArr.filter((ele) => {
          return ele.isFile && ele.name.indexOf(that.filterName.trim()) === -1;
        });
        treeObj.showNodes(nodeArr);
        treeObj.hideNodes(that.dataList);
      } else {
        treeObj.showNodes(nodeArr);
      }
    },

    updateTreeNodeBySuffix(treeObj, treeNode) {
      let _this = this;
      if (!treeNode.isParent) return;
      let path = this.$api.processingApi.getFileListByPath;
      let param = {
        path: treeNode.id,
        tag: treeNode.tag, //用户目录：user 共享目录：public
        filter: _this.currentSelectSuffix,
        /*    filterName: _this.filterName*/
      };
      _this.http.get(path, param).then((res) => {
        let data = res.data;
        if (data.code == 0 && data.success) {
          treeNode.lastSuffix = _this.currentSelectSuffix;
          treeObj.removeChildNodes(treeNode);
          treeObj.addNodes(
            treeNode,
            this.getShowFileNodeData(data.data),
            false
          );

          this.getSelectResultData();
        }
      });
    },
    /**
     * item 参数信息{name:''],type:{name:'',plural:''},....} 目前其中type属性必须有
     * isBatch 文件选择是否是批量 批量（多景处理）多选文件路径间的分隔符以"#HT#" 常规的以"#TASK#"隔开
     */
    initFileTree(item, isBatch) {
      this.menuModalWidth = 1000;
      if (item.type.name.toLowerCase() === "file") {
        this.saveAsName = "新建文件";
      } else if (item.type.name.toLowerCase() === "dir") {
        this.saveAsName = "新建文件夹";
      }
      this.isBatch = isBatch;
      this.getSuffixOptions(item);
      this.ztreeSetting(item);
      this.collectItem = item;
    },
    handleShow(val){
      console.log(val)
      this.handleButton = val;
    },

    menuCancel() {
      this.$emit("closed");
      this.reset();
    },

    menuOk() {
      //根据树节点选中的节点组合选中结果
      // var treeObj = this.ztreeObjInstance,
      //   nodes = treeObj.getCheckedNodes(true);
      // let tempNode = "";
      // for (var index in nodes) {
      //   tempNode = nodes[index];
      //   if (
      //     this.currentItem.type.name.toLowerCase() === "file" &&
      //     tempNode.isParent
      //   )
      //     continue;
      //   if (info == "") info = tempNode.id;
      //   else if (this.isBatch) {
      //     info += "#HT#" + tempNode.id;
      //   } else {
      //     info += "#TASK#" + tempNode.id;
      //   }
      // }
      //根据列表选中数据组合结果
      if (this.resultData.length < 1) {
        this.$Message.info('没有可操作的文件，请先选择文件！');
        return

      }
      let info = "";
      console.log(this.resultData)
      this.resultData.forEach((ele) => {
        if (info == "") info = ele.path;
        else if (this.isBatch) {
          info += "#HT#" + ele.path;
        } else {
          info += "#TASK#" + ele.path;
        }
      });
      this.currentItem.default = info;
      
      this.$emit("menuOk", info);
      this.reset();
    },
    handleWorkflow(){
      //根据列表选中数据组合结果
      if (this.resultData.length < 1) {
        this.$Message.info('没有可操作的文件，请先选择文件！');
        return
      }
      let info = "";
      console.log(this.resultData)
      this.resultData.forEach((ele) => {
        if (info == "") info = ele.path;
        else if (this.isBatch) {
          info += "#HT#" + ele.path;
        } else {
          info += "#TASK#" + ele.path;
        }
      });
      this.currentItem.default = info;
      
      this.$emit("handleWorkflow", info);
      this.reset();
    },
    suffixSearch() {
      var treeObj = this.ztreeObjInstance,
        nodes = treeObj.getSelectedNodes(true);
      if (nodes.length < 1) return;
      for (var i in nodes) {
        // this.getFile(treeObj, nodes[i]);
        this.updateTreeNodeBySuffix(treeObj, nodes[i]);
      }
    },
    createNewFolder() {
      let _this = this;
      let treeObj = this.ztreeObjInstance;
      if (treeObj == null) {
        this.$Message.warning("请选择文件夹！");
        return;
      }
      let selectNodes = treeObj.getSelectedNodes();
      if (selectNodes.length < 1) {
        this.$Message.warning("请选择文件夹节点！");
        return;
      }
      if (!selectNodes[0].isParent) {
        this.$Message.warning("请选择文件夹！");
        return;
      }
      this.newFileName = ""; //界面文件名置为空
      this.createFolderModal = true;
      this.folderInput = true;
      if (this.currentItem.type.name.toLowerCase() === "file") {
        _this.isFile = true;
        this.folderInput = false;
        this.fileInput = true;
      }
      //用于新增文件或文件夹标识
      else {
        this.folderInput = true;
        this.fileInput = false;
        _this.isFile = false;
      }
    },
    showSelectedData() {
      let _this = this;
      _this.resultTableShow = !_this.resultTableShow;
      if (_this.resultTableShow) {
        _this.menuModalWidth = 1000;
      } else {
        _this.menuModalWidth = 800;
      }
    },
    getSelectResultData() {
      let _this = this;
      _this.resultData = [];
      var treeObj = this.ztreeObjInstance,
        nodes = treeObj.getCheckedNodes(true);

      for (var index in nodes) {
        let tempNode = nodes[index];
        if (
          this.currentItem.type.name.toLowerCase() === "file" &&
          tempNode.isParent
        ) {
          continue;
        }
        let tempObj = {};
        tempObj.name = tempNode.name;
        tempObj.path = tempNode.id;
        _this.resultData.push(tempObj);
      }
      _this.resultDataTotal = _this.resultData.length;
    },
    getSuffixOptions(item) {
      let _this = this;
      this.currentItem = item;
      if (!item.hasOwnProperty("constraint")) {
        _this.suffixOptions = [];
        _this.currentSelectSuffix = "";
        return;
      }
      let extensionsString = item.constraint.extensions;
      if (!extensionsString) return;

      let extensions = item.constraint.extensions.split(/[,;]/);
      extensions = extensions.filter((ele) => ele.indexOf("*.") != -1); //后缀筛选  格式必须是“ *.后缀名” 比如 *.tif;*.tiff
      //具体过滤条件
      let tempSuffix = [];
      for (var i in extensions) {
        let name = extensions[i];
        tempSuffix.push({ label: name, value: name.substring(2, name.length) });
      }
      //增加全部的过滤
      if (extensions.length > 1) {
        tempSuffix.unshift({
          label: extensions.join(";"),
          value: extensions.join("").split("*.").join(";").replace(";", ""), //将"*.tiff;*.img" 变成 "tiff;img"
        });
      }
      //增加其他类型
      tempSuffix.push({ label: "其他（*.*）", value: "" });

      //指定特殊的过滤条件显示在最上面
      // if (tempSuffix.filter((item) => item.value === "tiff").length > 0) {
      //   tempSuffix = tempSuffix.filter((item) => item.value != "tiff");
      //   tempSuffix.unshift({ label: "*.tiff", value: "tiff" }); //在最开始的地方加入并返回新数组
      // }

      _this.suffixOptions = tempSuffix;
      _this.currentSelectSuffix = tempSuffix[0].value;
    },

    ztreeSetting(item) {
      let _this = this;
      let checkType = { Y: "", N: "" }; //父与子的关联去掉0
      if (item.type.name.toLowerCase() === "file") {
        checkType = { Y: "s", N: "ps" };
      }
      let setting = {
        edit: {
          enable: true,
          drag: {
            isMove: true,
            prev: true,
            autoOpentime: 0,
          },
          editNameSelectAll: false,
          showRenameBtn: false, //zTree节点重命名功能
          showRemoveBtn: false, //zTree节点删除功能
        },
        check: {
          enable: true,
          nocheckInherit: false,
          chkboxType: checkType,
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            nameKey: "name",
          },
        },
        callback: {
          // beforeClick: this.beforeClick,
          onClick: this.zTreeOnClick,
          onCheck: this.zTreeOnCheck,
          onExpand: this.zTreeOnClick,
        },
        view: {
          showLine: false,
          showIcon: true,
          selectMulti: true,
          addHoverDom: this.addHoverDom,
          removeHoverDom: this.removeHoverDom,
        },
      };

      let urlPath = this.$api.processingApi.getDir + this.requestType;
      let param = {
        userName: window.sessionStorage.getItem("user"),
      };
      this.http.get(urlPath, param).then((res) => {
        let data = res.data;
        this.ztreeNode = res.data.data;
        this.$store.commit("setCollectTreeNode", res.data.data);
        this.dataListOne = res.data.data[0]; //记录用户收藏目录节点
        if (data.success == true) {
          // let treenNodeData = this.getShowFileNodeData(data.data);
          this.ztreeObjInstance = $.fn.zTree.init(
            $("#" + _this.ztreeId),
            setting,
            this.getCollectTreeNode
          );

          let nodes = this.ztreeObjInstance.getNodes();
          // this.ztreeObjInstance.expandNode(nodes[0], true, false, false);
          this.ztreeObjInstance.expandNode(nodes[0], true, false, false); //三个节点全部展开
          this.ztreeObjInstance.expandNode(nodes[1], true, false, false);
          this.ztreeObjInstance.expandNode(nodes[2], true, false, false);
          this.ztreeObjInstance.selectNode(nodes[0], false);
          // this.updateTreeNodeBySuffix(this.ztreeObjInstance, nodes[1]);
        }
      });
    },

    addHoverDom(treeId, treeNode) {
      const item = document.getElementById(`${treeNode.tId}_a`);
      /**
       *删除按钮（收藏目录下的文件 才可以删除）
       */
      if (
        item &&
        !item.querySelector(".tree_extra_deleteBtn") &&
        treeNode.isDelete == true //可以删除的字段   isDelete: true
      ) {
        this.node = treeNode; //记录当前节点
        this.deletePath = treeNode.path; //删除路径
        const deleteBtn = document.createElement("img");
        deleteBtn.id = `${treeId}_${treeNode.id}_deleteBtn`;
        deleteBtn.classList.add("tree_extra_deleteBtn");
        deleteBtn.src = require("../../assets/icons/delete.svg");
        deleteBtn.style.width = "15px";
        deleteBtn.style.height = "15px";
        // deleteBtn.style.marginLeft = "5px";
        // deleteBtn.style.marginBottom = "12px";
        deleteBtn.title = "删除";
        deleteBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          // this.selectTreeNodeId = treeNode.tId;
          this.delShow = true;
        });
        item.appendChild(deleteBtn);
      }
      /**
       *重命名按钮（收藏的文件重命名）
       */
      if (
        item &&
        !item.querySelector(".tree_extra_reNameBtn") &&
        treeNode.isDelete == true
      ) {
        this.node = treeNode; //记录当前节点
        this.editPath = treeNode.path; //重命名路径
        const reNameBtn = document.createElement("img");
        reNameBtn.id = `${treeId}_${treeNode.id}_reNameBtn`;
        reNameBtn.classList.add("tree_extra_reNameBtn");
        reNameBtn.src = require("../../assets/icons/edit.svg");
        reNameBtn.style.width = "15px";
        reNameBtn.style.height = "15px";
        reNameBtn.style.marginLeft = "5px";
        // deleteBtn.style.marginBottom = "12px";
        reNameBtn.title = "重命名";
        reNameBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          this.editName = treeNode.name;
          this.editShow = true; //重命名的Modal框
        });
        item.appendChild(reNameBtn);
      }
      /**
       *提示文件路径不存在按钮
       */
      if (
        item &&
        !item.querySelector(".tree_extra_changeBtn") &&
        treeNode.isDelete == true &&
        treeNode.isExist == false
      ) {
        this.node = treeNode; //记录当前节点
        // this.editPath = treeNode.path; //重命名路径
        const changeBtn = document.createElement("img");
        changeBtn.id = `${treeId}_${treeNode.id}_reNameBtn`;
        changeBtn.classList.add("tree_extra_changeBtn");
        changeBtn.src = require("../../assets/icons/clear.png");
        changeBtn.style.width = "15px";
        changeBtn.style.height = "15px";
        changeBtn.style.marginLeft = "5px";
        changeBtn.title = "文件路径不存在";
        changeBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          // this.editName = treeNode.name;
          // this.editShow = true; //重命名的Modal框
          this.changeShow = true;
        });
        item.appendChild(changeBtn);
      }
      /**
       *收藏按钮（共享文件和用户文件 才能进行收藏）
       */

      if (
        item &&
        !item.querySelector(".tree_extra_collectBtn") &&
        treeNode.isDelete == false &&
        treeNode.pid != -1
      ) {
        this.node = treeNode; //记录当前节点
        this.collectPath = treeNode.path; //记录当前节点的路径
        const collectBtn = document.createElement("img");
        collectBtn.id = `${treeId}_${treeNode.id}_reNameBtn`;
        collectBtn.classList.add("tree_extra_collectBtn");
        collectBtn.src = require("../../assets/icons/shoucang.png");
        collectBtn.style.width = "15px";
        collectBtn.style.height = "15px";
        collectBtn.style.marginLeft = "5px";
        // deleteBtn.style.marginBottom = "12px";
        collectBtn.title = "收藏";
        collectBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          this.collectShow = true;
        });
        item.appendChild(collectBtn);
      }
    },

    removeHoverDom(treeId, treeNode) {
      const item = document.getElementById(`${treeNode.tId}_a`);
      if (item) {
        const reNameBtn = item.querySelector(".tree_extra_reNameBtn"); //重命名
        const collectBtn = item.querySelector(".tree_extra_collectBtn"); //收藏
        const deleteBtn = item.querySelector(".tree_extra_deleteBtn"); //删除
        const changeBtn = item.querySelector(".tree_extra_changeBtn"); //路径不存在按钮
        // const historyBtn = item.querySelector('.tree_extra_historyBtn');
        if (reNameBtn) {
          item.removeChild(reNameBtn);
        }
        if (collectBtn) {
          item.removeChild(collectBtn);
        }
        if (deleteBtn) {
          item.removeChild(deleteBtn);
        }
        if (changeBtn) {
          item.removeChild(changeBtn);
        }
      }
    },

    zTreeOnClick(event, treeId, treeNode) {
      let _this = this;
      let path = this.$api.processingApi.getFileListByPath;
      let param = {
        path: treeNode.id,
        tag: treeNode.tag,
        filter: _this.currentSelectSuffix,
      };
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      treeObj.selectNode(treeNode);
      let sNode = treeObj.getSelectedNodes();
      if (sNode.length > 0 && treeNode.isParent) {
        // let zAsync = sNode[0].zAsync;
        // treeObj.reAsyncChildNodes(treeNode, "refresh");
        // if (zAsync) {
        // } else {
        //查询条件筛选 如果当前treeNode 的lastSuffix和当前的查询过滤条件一直时，不在查询避免页面节点返回的数据和当前的一致导致页面闪动问题
        if (treeNode.lastSuffix === this.currentSelectSuffix) {
          return;
        } else if (!treeNode.lastSuffix && treeNode.children) {
          //第一次已经返回数据了，但是lastSuffix没赋值时的处理
          return;
        }
        this.http.get(path, param).then((res) => {
          let data = res.data;
          if (data.success == true) {
            treeNode.halfCheck = false;
            treeNode.lastSuffix = _this.currentSelectSuffix;
            if (!treeNode.children) {
              treeObj.addNodes(
                treeNode,
                this.getShowFileNodeData(data.data),
                false
              );
            } else if (data.data.length > 0) {
              treeObj.removeChildNodes(treeNode);
              treeObj.addNodes(
                treeNode,
                this.getShowFileNodeData(data.data),
                false
              );
            }
            this.selectFileName();
            //   sNode[0].zAsync = true;
          }
        });
        // }
      }
    },
    zTreeOnCheck(event, treeId, treeNode) {
      var treeObj = $.fn.zTree.getZTreeObj(treeId),
        nodes = treeObj.getCheckedNodes(true);
      let item = this.currentItem;
      let type = ["dem_select", "base_index_select", "ref_select"];

      if (
        item.type.name.toLowerCase() === "file" ||
        type.indexOf(item.type.name.toLowerCase()) != -1
      ) {
        this.getFile(treeObj, treeNode);
        this.getSelectResultData(treeObj);
        return;
      }
      if (item.type.name.toLowerCase() === "dir") {
        if (!treeNode.isParent) {
          this.$Message.warning("请选择文件夹！");
          treeNode.checked = false;
          treeObj.updateNode(treeNode);
          return;
        } else {
          if (!item.type.plural && nodes.length > 1) {
            //限制单个文件夹
            this.$Message.warning("当前算法限制只能选一个文件夹哦！");
            treeNode.checked = false;
            treeObj.updateNode(treeNode);
            return;
          } else {
            this.getSelectResultData(treeObj);
          }
        }
      }
    },
    //参数为文件夹时，树节点不显示文件
    getShowFileNodeData(data) {
      if (this.currentItem.type.name.toLowerCase() === "dir") {
        //表示文件夹
        //过滤掉文件,只显示文件夹
        data = data.filter((ele) => !ele.isFile);
        return data;
      } /*else if (this.currentItem.type.name.toLowerCase() === "file" && this.filterName) {
        data = data.filter((ele) => {
         return  !ele.isFile || ele.isFile&&(ele.name.indexOf(this.filterName.trim())!=-1);
        });
        return data;
      } */ else {
        return data;
      }
    },
    getFile(treeObj, treeNode) {
      let childsArr = [];
      if (treeNode.children && treeNode.checked) {
        this.getChildsByTreeNode(treeNode, childsArr);
        this.getFileBySuffix(treeObj, childsArr);
      } else if (treeNode.checked) {
        let flag = false;
        // let suffix = this.currentSelectSuffix.toLowerCase();
        let fileName = treeNode.name.toLowerCase();
        flag = this.isFileHaveSuffix(fileName);

        // /!suffix.hasOwnProperty("value")
        if (!flag && treeNode.isFile) {
          treeNode.checked = false;
          this.$Message.warning("文件格式不符合过滤条件");
        }

        treeObj.updateNode(treeNode);
      }
    },
    //判断文件是否包含后缀
    isFileHaveSuffix(fileName) {
      let result = false;
      let regValue = "";
      let suffixArr = this.currentSelectSuffix.toLowerCase().split(";");
      for (let i = 0; i < suffixArr.length; i++) {
        regValue = fileName
          .substring(fileName.length - suffixArr[i].length, fileName.length)
          .toLowerCase();
        if (regValue === suffixArr[i]) {
          result = true;
          break;
        }
      }
      return result;
    },
    getChildsByTreeNode(treeNode, childsArr) {
      if (treeNode.isParent) {
        //是父节点获取所有子节点
        let childs = treeNode.children;
        for (var i in childs) {
          childsArr.push(childs[i]);
          this.getChildsByTreeNode(childs[i], childsArr);
        }
      }
      return childsArr;
    },
    getFileBySuffix(treeObj, childsFiles) {
      let nodes = childsFiles;
      let fileName;
      let tempNode;
      if (nodes.length == undefined && !nodes.isParent) {
        //文件
        fileName = nodes.name.toLowerCase();
        if (this.isFileHaveSuffix(fileName)) nodes.checked = true;
        else nodes.checked = false;
        treeObj.updateNode(nodes);
      }
      for (var i = 0; i < nodes.length; i++) {
        tempNode = nodes[i];
        this.getFileBySuffix(treeObj, tempNode);
        if (tempNode.isParent) {
          let tempChilds = tempNode.children;
          let num = 0;
          for (var m in tempChilds) {
            if (tempChilds[m].checked) num++;
            if (num > 1) break;
          }
          if (num < 1) {
            tempNode.checked = false;
            treeObj.updateNode(tempNode);
          }
        }
      }
    },
    deletePathRow(item, index) {
      let _this = this;
      _this.resultData.splice(index, 1);
      _this.resultDataTotal = _this.resultData.length;

      let treeObj = this.ztreeObjInstance;
      let node = treeObj.getNodeByParam("id", item.path);
      node.checked = false;
      treeObj.updateNode(node);

      let parentNode = node.getParentNode();
      let checkList = parentNode.children.filter((item) => item.checked);
      if (checkList.length < 1) {
        parentNode.checked = false;
        treeObj.updateNode(parentNode);
      }
    },
    reset() {
      let _this = this;
      _this.resultData = [];
      _this.resultDataTotal = _this.resultData.length;
      // _this.resultTableShow = false;
      // if (_this.resultTableShow) {
      //   _this.menuModalWidth = 1000;
      // } else {
      //   _this.menuModalWidth = 800;
      // }
      // let treeObj = $.fn.zTree.getZTreeObj(this.ztreeId);
      // treeObj.destroy();
    },
    createFolderOk() {
      let _this = this;
      let fileName = this.newFileName;

      let treeObj = this.ztreeObjInstance;
      let selectNodes = treeObj.getSelectedNodes();
      let newNode = null;

      if (selectNodes.length < 1) {
        this.$Message.warning("请先选择创建的位置!");
        return;
      }
      if (!fileName || !fileName) {
        this.$Message.warning("文件夹名称为空，请重写填写");
        return;
      }
      if (this.isFile) {
        //文件 判断文件名是否符合带后缀
        let a = fileName.split("").reverse().join("");
        let b = a.substring(0, a.search(/\./)).split("").reverse().join("");
        if (b == null || b == "") {
          this.$Message.warning("该文件名无效，没有后缀");
          return;
        }
        newNode = {
          name: fileName,
          id: selectNodes[0].id + "/" + fileName,
          isParent: false,
        };
        if (newNode == null) return;
        this.createFolderModal = false;
        treeObj.addNodes(selectNodes[0], 0, newNode, true); //新增节点放在文件夹的顶层并默认选择
        let node = selectNodes[0].children[0];
        node.checked = true;
        treeObj.updateNode(node);
        this.getSelectResultData();
      } else {
        newNode = {
          name: fileName,
          id: selectNodes[0].id + "/" + fileName,
          isParent: true,
        };
        if (newNode == null) return;
        let path = _this.$api.processingApi.dirCreate;
        _this.createFolder(path, fileName, treeObj, selectNodes, newNode);
      }
    },
    createFolder(path, fileName, treeObj, selectNodes, newNode) {
      let _this = this;
      let param = {
        dirName: fileName,
        parentPath: selectNodes[0].id,
      };
      _this.http.post(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          this.createFolderModal = false;
          treeObj.addNodes(selectNodes[0], 0, newNode, true); //新增节点放在文件夹的顶层并默认选择
          let node = selectNodes[0].children[0];
          node.checked = true;
          treeObj.updateNode(node);
          this.getSelectResultData();
        } else {
          _this.$Message.error(res.data.message);
        }
      });
    },
    createFolderCancel() {
      this.createFolderModal = false;
    },
  },
};
</script>
<style scoped>
.modalContent {
  display: flex;
}

.treeDiv {
  height: 500px;
  flex: 1;
  overflow-y: auto;
}
.resultDiv {
  width: 380px;
}
.selectNumberClass {
  margin-left: 10px;
}
.resultTableStyle {
  margin-left: 10px;
  margin-right: 10px;
  text-align: center;
}
.saveFileStyle {
  width: 280px;
}
.selectSuffix {
  /* padding-left: 10px; */
  margin-left: -20px;
  margin-bottom: 0rem;
}
</style>
